<template>
  <el-form ref="ruleFormRef" :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px">
    <el-form-item label="主题" prop="title">
      <el-input v-model="formData.title" placeholder="请填写主题" maxlength="32" size="small" />
    </el-form-item>
    <el-form-item label="员工" prop="staffId">
      <el-select v-model="formData.staffId" placeholder="请选择员工" size="small" filterable>
        <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="奖惩日期" prop="actionStartTime">
      <el-date-picker v-model="formData.occurDate" type="date" placeholder="请选择奖惩日期" size="small"/>
    </el-form-item>
    <el-form-item label="奖惩" prop="bonusPenaltyType">
      <el-radio-group v-model="formData.bonusPenaltyType" size="small">
        <el-radio :label="0">奖励</el-radio>
        <el-radio :label="1">惩罚</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="奖惩类别" prop="bonusPenaltyClassify">
      <el-select v-model="formData.bonusPenaltyClassify" placeholder="请选择奖惩类别" size="small">
        <el-option v-for="item in dictMap[formData.bonusPenaltyType == 0 ? 'StaffBonusType' : 'StaffPenaltyType']" :key="item.value" :value="item.value" :label="item.name" />
      </el-select>
    </el-form-item>
    <el-form-item label="奖惩金额" prop="amount">
      <el-input-number v-model="formData.amount" :precision="2" :controls="false" :max="99999999" :min="-99999999" size="small" />
    </el-form-item>
    <el-form-item label="奖惩内容" prop="content">
      <editor v-model="formData.content" />
    </el-form-item>
    <el-form-item label="奖惩原因" prop="reason">
      <el-input v-model="formData.reason" placeholder="请填写奖惩原因" size="small" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item label="优先度" prop="priority">
      <el-radio-group v-model="formData.priority" size="small">
        <el-radio :label="0" size="small">普通</el-radio>
        <el-radio :label="1" size="small">高</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注信息" prop="remark">
      <el-input v-model="formData.remark" placeholder="请填写奖惩原因" size="small" type="textarea" :rows="3" />
    </el-form-item>
  </el-form>
</template>

<script>
// 奖惩 OA_BONUS_PENALTY
import {onMounted, reactive, toRefs, ref, nextTick, watch} from 'vue'
import {getDictByCodes} from '/@/api/sys/dict'
import {listByState} from '/@/api/oa/staff'
import Editor from '/@/components/editor/index.vue'
import {homeApi} from "/@/api/home/index";
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
  name: 'BonusPenalty',
  components: {
    Editor
  },
  props: {
    selectTime: {
      type: String,
      default: null
    },
    editId: {
      type: String,
      default: null
    }
  },
  setup(props) {
    const { selectTime, editId } = toRefs(props)
    const homeCalendar = homeApi();
    const ruleFormRef = ref({})
    const storesCalendarConfig = useCalendarConfig();
    const { eventForm } = storeToRefs(storesCalendarConfig)
    const state = reactive({
      formData: {
        title: '员工奖惩',
        staffId: null,
        occurDate: null,  // 奖惩日期/时间
        bonusPenaltyType: 0,   // 奖惩 0奖励 1惩罚
        bonusPenaltyClassify: null,   // 奖惩类别，奖励时字典StaffBonusType，惩罚时字典StaffPenaltyType
        content: null,    // 奖惩内容
        reason: null,   // 奖惩原因
        amount: 0.00,   // 奖惩金额
        remark: null,   // 备注信息
        state: 2,           // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
        priority: 0        // 优先级 0普通 1重要
      },
      formRules: {
        title: {required: true, message: '请填写主题', trigger: 'blur'},
        staffId: {required: true, message: '请选择员工', trigger: 'change'},
        occurDate: {required: true, message: '请选择奖惩日期', trigger: 'change'},
        bonusPenaltyType: {required: true, message: '请选择奖/惩', trigger: 'change'},
        bonusPenaltyClassify: {required: true, message: '请选择奖惩类别', trigger: 'change'},
        content: {required: true, message: '请填写奖惩内容', trigger: 'blur'},
        reason: {required: true, message: '请填写奖惩原因', trigger: 'blur'}
      },
      dictMap: {},
      staffList: [],
      originForm: {}
    })
    const getStaffData = async () => {
      try {
        const res = await listByState('')
        state.staffList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const submit = () => {
      if(!ruleFormRef) return
       return new Promise(async (resolve, reject) => {
        await ruleFormRef.value.validate((valid, fields) => {
          if (valid) {
            if(editId.value) {
              // 编辑
              for(let key in state.formData){
                if(state.originForm.hasOwnProperty(key)){
                  state.originForm[key] = state.formData[key]
                }
                if(state.originForm.info.hasOwnProperty(key)){
                  state.originForm.info[key] = state.formData[key]
                }
              }
              storesCalendarConfig.setEventForm(state.originForm)
              reset()
              close()
              resolve('edit') 
            }else{
              homeCalendar.addBonusPenalty(state.formData).then((res) => {
                if (res.code === 0) {
                  reset()
                  close()
                  resolve()
                }
              });
            }
          } else {
              reject()
              console.log("error submit!", fields);
          }
        })  
       })
    }
    const reset = () => {
      if (!ruleFormRef) return
      ruleFormRef.value.resetFields()
    }
    watch(() => eventForm.value,
      val => {
        if(editId.value && val) {
          // 编辑
          nextTick(() => {
            const data = val
            if(!data) return
            state.originForm = data
            for(let params in data.info){
              // 拿出info里面的数据
              if(state.formData.hasOwnProperty(params)) {
                state.formData[params] = data.info[params]
              }
            }
            for(let key in data) {
              // 列表里面的数据
              if(state.formData.hasOwnProperty(key)) {
                state.formData[key]= data[key]
              }
            }
          })
        }
      }        
    )
    onMounted(() => {
      getDictByCodes(['StaffBonusType', 'StaffPenaltyType']).then(res => state.dictMap = res.data).catch(e => console.log(e))
      getStaffData()
      nextTick(() => {
        if(!editId.value && selectTime.value) {
          state.formData.occurDate = selectTime.value.substring(0, 10)
        }
      })
    })

    return {
      ...toRefs(state),
      getStaffData,
      ruleFormRef,
      submit,
      reset
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
